package com.itheima.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.itheima.pojo.Result;
import com.itheima.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
@Slf4j
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override // controller方法前
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle...");
        //        获取请求url地址
        String url = request.getRequestURI().toString();
        log.info("请求的url,{}", url);
        if (url.contains("login")) {
            log.info("登陆操作");
            return true;
        }
        String jwt = request.getHeader("token");
        if (!StringUtils.hasLength(jwt)) {
            log.info("请求头token为空");
//            要将其转换为json
            Result err = Result.Error("NOT_LOGIN");
            String nologin = JSONObject.toJSONString(err);
            response.getWriter().write(nologin);
            return false;
        }
//        校验jwt令牌
        try {
            JwtUtils.parseJwt(jwt);
        } catch (Exception e) { // 解析失败
            e.printStackTrace();
            log.info("解析令牌失败");
            Result err = Result.Error("NOT_LOGIN");
            String nologin = JSONObject.toJSONString(err);
            response.getWriter().write(nologin);
            return false;
        }
//       令牌解析成功 放行
        log.info("令牌解析成功,放行");
        return true;
    }

    @Override // controller方法后
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle...");
    }

    @Override // 最后执行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion...");
    }
}
